package com.app.configuration.web.filter;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 防止xssFilter注入
 * @author chenl
 *
 */
@Configuration
@WebFilter(urlPatterns = "/*", filterName = "xssFilter")
public class XssFilter implements Filter{

	private static final Logger log = Logger.getLogger(XssFilter.class);
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		log.info("xssFilter执行init");
	}
	
	
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		//对xss注入进行处理
        HttpServletResponse rep = (HttpServletResponse) response;  
        HttpServletRequest req = new XSSRequestWrapper((HttpServletRequest) request);
        
//        Cookie[] cookies = req.getCookies();
//        if(cookies!=null) {
//	        for(Cookie cookie : cookies){ 
//	          cookie.setHttpOnly(true); 
//	          String value = cookie.getValue(); 
//	          System.out.println("session value:"+value);
//	                StringBuilder builder = new StringBuilder(); 
//	                builder.append("JSESSIONID=" + value + "; "); 
//	                builder.append("Secure; "); 
//	                builder.append("HttpOnly; "); 
//	                Calendar cal = Calendar.getInstance(); 
//	                cal.add(Calendar.HOUR, 1); 
//	                Date date = cal.getTime(); 
//	                Locale locale = Locale.CHINA; 
//	                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss",locale); 
//	                builder.append("Expires=" + sdf.format(date)); 
//	                rep.setHeader("Set-Cookie", builder.toString()); 
//	        }
//        } 
        
//        HttpServletResponse rep = (HttpServletResponse) response;  
        
        rep.setHeader("x-frame-options", "SAMEORIGIN");
        rep.setHeader("Content-Security-Policy","frame-ancestors 'self'"); 
        
        rep.setHeader("Access-Control-Allow-Origin", "*");
        rep.setHeader("Cache-Control","no-cache"); 
//        rep.setHeader("Access-Control-Allow-Origin", "*");
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        
//        rep.setHeader("Access-Control-Allow-Origin", "*");
        rep.setHeader("Access-Control-Allow-Credentials", "true");
//        rep.setHeader("Access-Control-Allow-Methods", "*");
        rep.setHeader("Access-Control-Allow-Headers", "Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, userId, token");
        rep.setHeader("Access-Control-Expose-Headers", "*");

//        if (req.getMethod().equals("OPTIONS")) {
//            HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
//            return;
//        }
//        HttpServletRequest req = new XSSRequestWrapper((HttpServletRequest) request);
        
        
        chain.doFilter(req, response);
        
	}
	
	
	
	
	
	
	class XSSRequestWrapper extends HttpServletRequestWrapper {
		
		public XSSRequestWrapper(HttpServletRequest servletRequest) {
	     	super(servletRequest);
	    }
	    @Override
	    public String[] getParameterValues(String parameter) {
	        String[] values = super.getParameterValues(parameter);
	        if (values == null) {
	            return null;
	        }
	        int count = values.length;
	        String[] encodedValues = new String[count];
	        for (int i = 0; i < count; i++) {
	            encodedValues[i] = stripXSS(values[i]);
	        }
	        return encodedValues;
	    }
	    
	    @Override
	    public String getParameter(String parameter) {
	        String value = super.getParameter(parameter);
	        return stripXSS(value);
	    }
	    
	    @Override
	    public String getHeader(String name) {
	        String value = super.getHeader(name);
	        return stripXSS(value);
	    }
	    
	    @Override
	    public Map<String, String[]> getParameterMap() {
	    	// TODO Auto-generated method stub
	    	Map<String,String[]> map = super.getParameterMap();
	    	Map<String,String[]> newMap = new HashMap<String,String[]>();
	    	for(Map.Entry<String,String[]> entry: map.entrySet()){
	    		String key = entry.getKey();
				String temp[] = entry.getValue();
				String newTemp[] = null;
				if(temp != null) {
					newTemp = new String[temp.length];
					for(int j=0;j<temp.length;j++) {
						String tempStr = temp[j];
						newTemp[j] = stripXSS(tempStr);
					}
				}
				newMap.put(key, newTemp);					
			}
	    	return newMap;
	    }
	    
	    private String stripXSS(String value) {
	    	
	    	String tip = "1111";
	        if (value != null) {	            
	            value = value.replaceAll(" (?i)where ", tip)
	    				.replaceAll(" (?i)exec ", tip)
	    				.replaceAll(" (?i)insert ", tip)
	    				.replaceAll(" (?i)delete ", tip)
	    				.replaceAll(" (?i)select ", tip)
	    				.replaceAll(" (?i)from ", tip)
	    				.replaceAll(" (?i)update ", tip)
	    				.replaceAll("(?i)alert", tip)
	    				.replaceAll("(?i)<script", tip)
	    				.replaceAll("(?i)onabort", tip)
	    				.replaceAll("(?i)onblur", tip)
	    				.replaceAll("(?i)onchange", tip)
	    				.replaceAll("(?i)onclick", tip)
	    				.replaceAll("(?i)ondblclick", tip)
	    				.replaceAll("(?i)onerror", tip)
	    				.replaceAll("(?i)onfocus", tip)
	    				.replaceAll("(?i)onkeydown", tip)
	    				.replaceAll("(?i)onkeypress", tip)
	    				.replaceAll("(?i)onkeyup", tip)
	    				.replaceAll("(?i)onload", tip)
	    				.replaceAll("(?i)onmousedown", tip)
	    				.replaceAll("(?i)onmousemove", tip)
	    				.replaceAll("(?i)onmouseout", tip)
	    				.replaceAll("(?i)onmouseover", tip)
	    				.replaceAll("(?i)onmouseup", tip)
	    				.replaceAll("(?i)onreset", tip)
	    				.replaceAll("(?i)onresize", tip)
	    				.replaceAll("(?i)onselect", tip)
	    				.replaceAll("(?i)onsubmit", tip)
	    				.replaceAll("(?i)onunload", tip)
	            
	    		        .replaceAll("(?i)vdslei", tip)
	    				.replaceAll(" (?i)ssion", tip)
	    				.replaceAll("(?i)<iframe", tip)
	    				//.replaceAll("(?i)http", tip)
	    				.replaceAll(" (?i)union ", tip)
	    				//.replaceAll(" (?i)document", tip)
	    				.replaceAll(" (?i)eval", tip)
	    				
	    				.replaceAll(" (?i)request", tip)
	    				
	    				.replaceAll(" (?i)parameter", tip)
	    				.replaceAll(" (?i)cookies", tip)
	    				
	    				
	    				.replaceAll(" (?i)or ", tip)
	    				//.replace("^", tip)
	    				//.replace("'", "‘")
	    				//.replace("'", "’")
	    				//.replace("$", tip)
	    				//.replace("<%", tip)
	    			
	    				.replaceAll(" (?i)expre", tip);
	            
	        }
	        
	        
	        return value;
	    }


	}

}
